package com.relife.sys.service;

import com.relife.common.exception.BusinessException;
import com.relife.common.quartz.CronTriggeManager;
import com.relife.common.quartz.CronTriggerMis;
import com.relife.core.dao.IBaseDao;
import com.relife.core.entity.CronEntity;
import com.relife.core.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service("cronService")
@Transactional
public class CronService extends BaseService {

	@Autowired
	private IBaseDao dao;

	/**
	 * 
	 * @author WU
	 * @date 2017年4月19日 下午5:20:13
	 * @param cron
	 * @throws Exception
	 */
	public void saveOrUpdateCron(CronEntity cron) throws Exception {
		if (cron.getId() != null) {
			CronTriggerMis mis = new CronTriggerMis();
			mis.setCronKey(cron.getId());
			mis.setName(cron.getName());
			CronTriggeManager.delCronTrigge(mis);
		}
		dao.saveOrUpdate(cron);
	}

	/**
	 * @author WU
	 * @param id
	 * @throws Exception
	 */
	public void isStart(String id, Integer state) throws Exception {
		CronEntity cron = dao.get(CronEntity.class, id);
		if (cron == null) {
			throw new BusinessException("找不到对应的数据");
		}
		cron.setState(state == 0 ? 1 : 0);

		CronTriggerMis mis = new CronTriggerMis();
		mis.setCronKey(cron.getId());
		mis.setName(cron.getName());
		mis.setServerName(cron.getServiceName());
		mis.setMethod(cron.getMethodName());
		mis.setCronExpression(cron.getCron());
		mis.setCronKey(cron.getId());
		if (cron.getState() == 0) {
			CronTriggeManager.delCronTrigge(mis);
		} else {
			CronTriggeManager.cronTrigge(mis);
		}
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年4月19日 下午5:25:54
	 * @param cron
	 * @throws Exception
	 */
	public void delCron(CronEntity cron) throws Exception {
		cron = dao.get(CronEntity.class, cron.getId());
		if (cron == null) {
			throw new BusinessException("找不到对应的数据");
		}
		CronTriggerMis mis = new CronTriggerMis();
		mis.setName(cron.getName());
		CronTriggeManager.delCronTrigge(mis);
		dao.delete(cron);
	}

	public void test() {
	}
}
